package controller

import (
	"github.com/gin-gonic/gin"
	"log/slog"
	"main/internal/entity"
	"net/http"
	"strconv"
)

type UserController struct {
}

// 访问获取 http://localhost:8000/controller/user?userId=123
func (this UserController) Index(ctx *gin.Context) {
	userId := ctx.Query("userId")
	slog.Info("获取到参数 userId--->%v", userId)

	ctx.JSON(200, gin.H{
		"msg": "用户新首页",
	})
}

// 访问获取 http://localhost:8000/controller/user/get/123
func (this UserController) Get(ctx *gin.Context) {
	userId := ctx.Param("userId")
	slog.Info("获取到path参数 userId--->%v", userId)

	ctx.JSON(200, gin.H{
		"msg":    "用户详情",
		"userId": userId,
	})
}

// 参考文档 https://blog.csdn.net/Octopus21/article/details/124404676
// 添加用户
// curl --location --request POST "http://localhost:8000/controller/user/add" --header "Content-Type: application/json" --data-raw "{ \"name\":\"冯晓东\",\"age\":18}"
func (this UserController) Add(ctx *gin.Context) {
	var userInfo entity.UserInfo
	if err := ctx.ShouldBind(&userInfo); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	slog.Info("用户姓名:%v,用户年龄%v", userInfo.Name, userInfo.Age)

	ctx.JSON(200, gin.H{
		"msg":  "用户详情",
		"user": userInfo,
	})
}

// 修改用户
// curl --location --request POST "http://localhost:8000/controller/user/update" --form "name=\"鱼刺\"" --form "age=\"17\""
func (this UserController) Update(ctx *gin.Context) {
	var userInfo entity.UserInfo
	userInfo.Name = ctx.PostForm("name")
	userInfo.Age, _ = strconv.Atoi(ctx.PostForm("age"))

	slog.Info("用户姓名:%v,用户年龄%v", userInfo.Name, userInfo.Age)

	ctx.JSON(200, gin.H{
		"msg":  "用户详情",
		"user": userInfo,
	})
}
